import 'package:flutter/material.dart';

/// 通用表单字段组件
class CommonFormField extends StatefulWidget {
  final String label;
  final String hintText;
  final ValueChanged<String>? onChanged;
  final String? initialValue;
  final TextInputType? keyboardType;
  final bool enabled;
  final FormFieldValidator<String>? validator;
  final String? errorText; // 添加外部错误文本支持

  const CommonFormField({
    super.key,
    required this.label,
    required this.hintText,
    this.onChanged,
    this.initialValue,
    this.keyboardType,
    this.enabled = true,
    this.validator,
    this.errorText,
  });

  @override
  State<CommonFormField> createState() => _CommonFormFieldState();
}

class _CommonFormFieldState extends State<CommonFormField> {
  final TextEditingController _controller = TextEditingController();
  bool _hasInteracted = false; // 跟踪用户是否已经与字段交互

  @override
  void initState() {
    super.initState();
    _controller.text = widget.initialValue ?? '';
    _controller.addListener(_onTextChanged);
  }

  @override
  void dispose() {
    _controller.removeListener(_onTextChanged);
    _controller.dispose();
    super.dispose();
  }

  void _onTextChanged() {
    if (widget.onChanged != null) {
      widget.onChanged!(_controller.text);
    }
    if (!_hasInteracted) {
      setState(() {
        _hasInteracted = true;
      });
    }
  }

  @override
  void didUpdateWidget(CommonFormField oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.initialValue != oldWidget.initialValue && 
        widget.initialValue != _controller.text) {
      _controller.text = widget.initialValue ?? '';
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          widget.label,
          style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
        ),
        const SizedBox(height: 8),
        TextFormField(
          controller: _controller,
          keyboardType: widget.keyboardType,
          enabled: widget.enabled,
          validator: widget.validator,
          decoration: InputDecoration(
            hintText: widget.hintText,
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(8.0),
            ),
            enabled: widget.enabled,
            errorText: widget.errorText != null && _hasInteracted 
                ? widget.errorText 
                : null, // 只有在用户交互后才显示错误
            contentPadding: const EdgeInsets.symmetric(
              horizontal: 12,
              vertical: 12,
            ),
          ),
        ),
      ],
    );
  }
}
